package com.example.peachgrove.controller.admin.file;

import com.alibaba.fastjson.JSON;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.IOUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.UUID;

@Api(tags = "文件操作")
@RestController
@RequestMapping("/file")
@ResponseBody
public class FileController {

    @Value("${qiniu.AccessKey}")
    private String AccessKey;

    @Value("${qiniu.SecretKey}")
    private String SecretKey;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.domainOfBucket}")
    private String domainOfBucket;

    @Value("${qiniu.expireInSeconds}")
    private String expireInSeconds;

    @ApiOperation("保存图片")
    @PostMapping("/saveImg")
    @ApiImplicitParams({
            @ApiImplicitParam(name="files",value="文件",dataTypeClass = MultipartFile.class, paramType = "query",example=""),
    })
    public HashMap saveImg(HttpServletRequest request) throws IOException {
        HashMap<String,Object> res = new HashMap();
        Configuration cfg = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(AccessKey, SecretKey);
        String token = auth.uploadToken(bucket);
        try{
            MultipartHttpServletRequest multipartRequest =
                    WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
            WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
            MultipartFile multipartFile = multipartRequest.getFile("image");
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String fileName = multipartFile.getOriginalFilename();
            InputStream inputStream = multipartFile.getInputStream();
            byte[] byteData = IOUtils.toByteArray(inputStream);
            Response response = uploadManager.put(byteData, uuid+"-"+fileName, token);
            inputStream.close();
            res.put("bash",domainOfBucket+ JSON.parseObject(response.bodyString()).getString("key"));
        }catch (Error e){
            res.put("Error",e);
        }

        return res;
    }

    @ApiOperation("存封面")
    @PostMapping("/saveCover")
    @ApiImplicitParams({
            @ApiImplicitParam(name="files",value="文件",dataTypeClass = MultipartFile.class, paramType = "query",example=""),
    })
    public HashMap saveCover(HttpServletRequest request) {
        HashMap<String, Object> res = new HashMap();
        Configuration cfg = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(AccessKey, SecretKey);
        String token = auth.uploadToken(bucket);
        try {
            MultipartHttpServletRequest multipartRequest =
                    WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
            WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
            MultipartFile multipartFile = multipartRequest.getFile("image");
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String fileName = multipartFile.getOriginalFilename();
            InputStream inputStream = multipartFile.getInputStream();
            byte[] byteData = IOUtils.toByteArray(inputStream);
            Response response = uploadManager.put(byteData, uuid + "-" + fileName, token);
            inputStream.close();
            StringBuffer sb = new StringBuffer();
            sb.append("domainOfBucket").append(JSON.parseObject(response.bodyString()).getString("key"));
            res.put("bash", sb.toString());
        }catch (Error | IOException e){
            res.put("Error",e);
        }
        return res;
    }

}
